package com.qiyee.dalligent;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class BarcodeGenerator3 {

    private static final Integer CODE_WIDTH = 100;                 // 基础属性：二维码宽度，单位像素
    private static final Integer CODE_HEIGHT = 30;                // 基础属性：二维码高度，单位像素
    private static final Integer FRONT_COLOR = 0x000000;           // 基础属性：二维码前景色，0x000000 表示黑色
    private static final Integer BACKGROUND_COLOR = 0xFFFFFF;      // 基础属性：二维码背景色，0xFFFFFF 表示白色

    public static void main(String[] args) throws Exception {

        //设置生成条形码的内容（注：条形码信息一定要按照格式，如随便一个商品上的条形码都行，但必须是EAN_13格式）
        String qrMessage = "8894796215296711"+ new Random().nextInt();

        // EncodeHintType：指定和控制码生成器的一些参数的类
        Map<EncodeHintType, Object> typeObjectHashMap = new HashMap<EncodeHintType, Object>();
        // 设置编码
        typeObjectHashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置容错等级
        typeObjectHashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置边距，默认为5
        typeObjectHashMap.put(EncodeHintType.MARGIN, 3);

        // MultiFormatWriter:用于写入条形码或二维码
        Code128Writer multiFormatWriter = new Code128Writer();
        BitMatrix bitMatrix = multiFormatWriter
            .encode(qrMessage, BarcodeFormat.CODE_128, CODE_WIDTH, CODE_HEIGHT, typeObjectHashMap);

        // java.awt.image.BufferedImage：把条形码信息转换为图像信息
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);;
       /* for (int x = 0; x < CODE_WIDTH; x++) {
            for (int y = 0; y < CODE_HEIGHT; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }*/

        // javax.imageio.ImageIO 将图片信息写出到文件

        String path = qrMessage + ".png";
        ImageIO.write(bufferedImage, "png", new FileOutputStream(path));
        exportToExcel(qrMessage,path);
    }
    public static void exportToExcel(String fileName,String barcodeFilePath) throws Exception{
        XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作簿
        XSSFSheet sheet = workbook.createSheet("Barcodes"); // 创建工作表
        sheet.autoSizeColumn(0);
        Row row = sheet.createRow(0);

        // 创建一个单元格对象
        Cell cell = row.createCell(0);

        // 设置单元格样式为包含图片
        CreationHelper helper = workbook.getCreationHelper();
        ClientAnchor anchor = helper.createClientAnchor();
        anchor.setCol1(cell.getColumnIndex()); // 图片从哪个单元格开始
        anchor.setRow1(row.getRowNum());
        anchor.setCol2(cell.getColumnIndex()+1 ); // 图片结束的单元格
        anchor.setRow2(row.getRowNum() );
        anchor.setDx1(100); // 距离开始单元格的x坐标
        anchor.setDy1(100); // 距离开始单元格的y坐标
        anchor.setDx2(100); // 距离结束单元格的x坐标
        anchor.setDy2(100); // 距离结束单元格的y坐标
        // 将图片插入到工作簿中
        int pictureIdx = workbook.addPicture(Files.readAllBytes(Paths.get(barcodeFilePath)), Workbook.PICTURE_TYPE_JPEG);
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        drawing.createPicture(anchor, pictureIdx);
        try {


            // 保存Excel文件
            try (FileOutputStream outputStream = new FileOutputStream(fileName+".xlsx")) {
                workbook.write(outputStream);
            }
            workbook.close(); // 关闭工作簿
        } catch (IOException e) {
            e.printStackTrace(); // 输出异常信息
        }
    }
}